<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Login extends CI_Controller {
	public function __construct(){
        session_start();
		parent::__construct();
        $this->load->library('form_validation');
        $this->load->helper('url');
        $this->load->helper('captcha');
	}

	public function index(){
        if (!$_SESSION['webmaster']['user_id']) {
            redirect(base_url().'login/login/');
        } else {
            redirect(base_url().'main/index');
        }
    }
	public function login(){
        $_SESSION['webmaster']['user_id'] && redirect();
        $vals = array(
            'img_path'      => '../static/captcha/',
            'img_url'       => 'http://master.odingweb.com/static/captcha/',
            'img_width'     => 70,
            'img_height'    => 23,
            'expiration'    => 200
        );
        $cap = create_captcha($vals);
        $data['image_code']=$cap;
        $_SESSION['webmaster']['code']=strtoupper($cap['word']);
        $this->load->view(THEME_PATH.'/login.php',$data);
	}

    public function logout(){
        unset($_SESSION['webmaster']);
        redirect(base_url().'login/login');
    }

    public function login_action(){
        $name=$this->input->post('user_name',true);
        $pass=md5($this->input->post('password',true));
        $code=strtoupper($this->input->post('code',true));

        $this->form_validation->set_rules('user_name', '用户名', 'required');
        $this->form_validation->set_rules('password', '密码', 'required');
        $this->form_validation->set_rules('code','验证码','required');
        !$this->form_validation->run() && e_json(validation_errors(),0);
		
        ($_SESSION['webmaster']['code']!=$code) && e_json('请输入正确的验证码',0);
        $query=$this->db->get_where('ca_userinfo',"user_name='$name'");
        !$query->num_rows() && e_json('该用户不存在',0);
        $query=$this->db->get_where('ca_userinfo',"password='$pass'");
        !$query->num_rows() && e_json('密码错误',0);
        $this->db->get_where('ca_userinfo',"user_name='$name' and password='$pass'");
        $user_row=$query->row_array();

        $_SESSION['webmaster']['user_id']   = $user_row['user_id'];
        $_SESSION['webmaster']['user_name'] = $user_row['user_name'];
        $this->db->update('ca_userinfo',"user_id='".$user_row['user_id']."'",array(
            'last_login_time' => time(),
            'last_login_ip'   => $this->input->ip_address()
        ));
        //$this->webmaster_log->add_manage_log('用户登录',__CLASS__,array('user_name'=>$name,'password'=>$pass));
        e_json('',1);
    }
}
?>